import { checkAuthorize } from '@/utils/authorize';
import { Content, Page } from '@alita/flow';
import { setPageNavBar, useLocation, useNavigate } from 'alita';
import {
  AutoCenter,
  Button,
  Cascader,
  Grid,
  InfiniteScroll,
  List,
  Modal,
  Picker,
  SearchBar,
  SelectorOption,
  Space,
  Tag,
  Toast,
} from 'antd-mobile';
import type {
  CascaderActions,
  CascaderOption,
  CascaderValueExtend,
} from 'antd-mobile/es/components/cascader';
import { CheckListValue } from 'antd-mobile/es/components/check-list';
import { Action } from 'antd-mobile/es/components/modal/modal-action-button';
import { PickerActions } from 'antd-mobile/es/components/picker';
import {
  PickerColumn,
  PickerColumnItem,
  PickerValue,
} from 'antd-mobile/es/components/picker-view';
import { ToastHandler } from 'antd-mobile/es/components/toast';

import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn'; // 导入本地化语言
import relativeTime from 'dayjs/plugin/relativeTime';
dayjs.extend(relativeTime);
dayjs.locale('zh-cn');

import { useEffect, useRef, useState } from 'react';
// import { OtherCountInPartake } from '@/components/partake';
import {
  DetailResult,
  PageInfo,
  type PageResult,
  type Study,
  type StrTreeItemType,
} from '@/pages/types/type';
import { getRequestInit, postRequestInit, urlPrefix } from '@/utils/http';
import { SearchBarRef } from 'antd-mobile/es/components/search-bar';
// import { DemoBlock } from '@/components/demos-util';

import DateSelectPopup, {
  ComplexDateSelectedValue,
  DateDefaultValue,
} from '@/components/date-range-selector';
import { DATE_TIME_FORMAT } from '@/constants';
import { LeadersPopup } from '@/pages/selectors/wei-xin-user';
import { useModel } from 'alita';
import { DownOutline } from 'antd-mobile-icons';
import styles from './index.less';
const numberFormator = new Intl.NumberFormat();

export default () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [pageInfo, setPageInfo] = useState<PageInfo>({
    totalPages: 0,
    page: 0,
    size: 15,
    code: 0,
    msg: '未搜索',
    totalElements: -1,
    last: false,
  });
  const [data, setData] = useState<Study[]>([]);
  const [hasMore, setHasMore] = useState(true);
  const [tokening, setTokening] = useState<boolean>(false);
  const [tokenFail, setTokenFail] = useState<string | undefined>(undefined);
  const [authOK, setAuthOK] = useState<boolean>(false);
  const [loadingTimes, setLoadingTimes] = useState<number>(1);
  const [loadFails, setLoadFails] = useState<string[]>([]);
  const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
  const searchRef = useRef<SearchBarRef>(null);
  const [name, setName] = useState<string>();
  const [page, setPage] = useState<number>(0);

  
  const [subjects, setSubjects] = useState<StrTreeItemType[]>([]);
  const [subject, setSubject] = useState<CheckListValue[]>([]);

  // 申请人，支持多选，2024-12-07
  const [applicantPopupVisable, setApplicantPopupVisable] =
    useState<boolean>(false);
  const [applicants, setApplicants] = useState<SelectorOption<string>[]>([]);

  // 申请时间
  const [createdDatePopupVisable, setCreatedDatePopupVisable] =
    useState<boolean>(false);
  const [createdDateValue, setCreatedDateValue] =
    useState<ComplexDateSelectedValue>(DateDefaultValue);

  // 最新状态
  const [livingTypes, setLivingTypes] = useState<PickerColumn[]>([]);
  const [lastLivingType, setLastLivingType] = useState<PickerValue[]>([]);
  const [invoiceSupplement, setInvoiceSupplement] = useState<PickerValue[]>([]);

  // 主要是支付状态
  const [livingTags, setLivingTags] = useState<PickerValue[]>([]);

  // 单据类型，预期支出，分摊单，补录数据等
  const [dogTypes, setDogTypes] = useState<PickerValue[]>([]);

  //
  const [originTypeTags, setOriginTypeTags] = useState<PickerValue[]>([]);

  const handler = useRef<ToastHandler>();

  async function doSearch(
    name: string | undefined = undefined,
    page: number = 0,
    subject: CheckListValue[] = [],
    // yearMonth: PickerValue[] = [],
    lastLivingType: PickerValue[] = [],
    invoiceSupplement: PickerValue[] = [],
    applicants: SelectorOption<string>[] = [],
    createdDateValue: ComplexDateSelectedValue = DateDefaultValue,
    dogTypes: PickerValue[] = [],
    originTypeTags: PickerValue[] = [],
    livingTags: PickerValue[] = [],
  ): Promise<PageResult<Reimb>> {
    try {
      const rsp: Response = await fetch(
        `${urlPrefix}/api/reimb-root-search`,
        postRequestInit({
          name,
          size: 15,
          page,
          subject,
          // yearMonth,
          lastLivingType,
          applicants,
          createdDateValue,
          invoiceSupplement:
            invoiceSupplement && invoiceSupplement.length > 0
              ? invoiceSupplement[0]
              : undefined,
          dogTypes,
          originTypeTags,
          livingTags,
        }),
      );
      if (rsp.ok) {
        return rsp.json();
      } else {
        return Promise.reject({ code: rsp.status, msg: rsp.statusText });
      }
    } catch (e) {
      return Promise.reject({ code: 1400, msg: `请求异常${e}` });
    }
  }

  function newSearch() {
    doSearch(
      name,
      page,
      subject,
      lastLivingType,
      invoiceSupplement,
      applicants,
      createdDateValue,
      dogTypes,
      originTypeTags,
      livingTags,
    )
      .then((rsp: PageResult<Reimb>) => {
        const { data, code, msg, page, size, totalElements, totalPages, last } =
          rsp;
        if (code === 0) {
          setData(data!);
          setPageInfo({
            code,
            msg,
            page,
            size,
            totalElements,
            totalPages,
            last,
          });
          setHasMore(!last);
        } else {
          setData([]);
          setLoadFails([...loadFails, msg]);
          setHasMore(false);
        }
      })
      .catch((reason) => {
        setLoadFails([...loadFails, reason]);
      })
      .finally(() => {
        console.log('searching complete!');
      });
  }

  function expertExcel() {
    const requddx = {
      name,
      subject,
      // yearMonth,
      lastLivingType,
      invoiceSupplement,
      applicants,
      createdDateValue,
      dogTypes,
      originTypeTags,
      livingTags,
    };

    handler.current = Toast.show({
      icon: 'loading',
      content: '正在下载',
      maskClickable: false,
      duration: 0,
    });

    fetch(
      `${urlPrefix}/api/reimb-root-search/export-excel`,
      postRequestInit(requddx),
    )
      .then(async (rsp: Response) => {
        if (rsp.ok) {
          await rsp
            .json()
            .then(async ({ data, code, msg }: DetailResult<string>) => {
              if (code === 0) {
                handler.current?.close();
                Modal.show({
                  title: '已导出',
                  closeOnAction: true,
                  actions: [
                    {
                      key: 'download',
                      text: (
                        <AutoCenter>
                          {' '}
                          <a href={data!} target="_blank" rel="noreferrer">
                            下载
                          </a>
                        </AutoCenter>
                      ),
                    },
                  ],
                  onAction: (action: Action, index: number) => {
                    console.log(action, ',index=', index);
                  },
                });
              } else {
                Toast.show({
                  icon: 'fail',
                  content: msg,
                  duration: 4000,
                });
              }
            })
            .catch((reason) => {
              Toast.show({
                icon: 'fail',
                content: `执行失败：${reason}`,
              });
            });
        }
      })
      .catch((reason: any) => {
        Toast.show({
          icon: 'fail',
          content: `执行失败：${reason}`,
        });
      })
      .finally(() => {
        //handler.current?.close();
      });
  }

  useEffect(() => {
    if (loadingTimes > 0) {
      return;
    }
    newSearch();
  }, [
    name,
    page,
    subject,
    //yearMonth,
    lastLivingType,
    invoiceSupplement,
    applicants,
    createdDateValue,
    dogTypes,
    originTypeTags,
    livingTags,
  ]);

  const model = useModel('useAuthModel');
  useEffect(() => {
    setPageNavBar({
      pagePath: location.pathname,
      navBar: { hideNavBar: true, pageTitle: `财务单据` },
    });
    checkAuthorize(
      (x) => setTokening(x),
      (y) => {
        setAuthOK(y);
      },
      (z) => setTokenFail(z),
      model,
    );
  }, []);

  function load() {
    if (authOK) {
      let times = 3;

      // 加载科目类型,代码生成器是：annotations.utils.TsCodeCreator // 生成搜索位置：2015-5239-2205-6402-2015
      const drbvr = `/api/subject-rel/str-tree`; // 生成代码搜索位置：2492-0412-5263-8850-4512-8512-3502
      fetch(`${urlPrefix}${drbvr}`, getRequestInit())
        .then(async (rsp: Response) => {
          if (rsp.ok) {
            await rsp
              .json()
              .then(
                async ({
                  data,
                  code,
                  msg,
                }: DetailResult<StrTreeItemType[]>) => {
                  if (code === 0) {
                    setLoadOK(msg);
                    setSubjects([{ value: '-1', label: '不限' }, ...data!]);
                  } else {
                    setLoadFails([...loadFails, msg]);
                  }
                },
              )
              .catch((reason) => {
                setLoadFails([...loadFails, reason]);
              })
              .finally(() => {
                console.log(`${drbvr} inner finally!`);
              });
          }
        })
        .catch((reason: any) => {
          console.error(reason);
          setLoadFails([...loadFails, `请求${drbvr}时发生错误：${reason}`]);
        })
        .finally(() => {
          console.log(`${drbvr} outter finally!`);
          setLoadingTimes(--times);
        });

      // 加载生命周期类型
      const mznmfl6 = `/api/reimb-living-type/leaves`;

      fetch(`${urlPrefix}${mznmfl6}`, getRequestInit())
        .then(async (rsp: Response) => {
          if (rsp.ok) {
            await rsp
              .json()
              .then(
                async ({
                  data,
                  code,
                  msg,
                }: DetailResult<PickerColumnItem[]>) => {
                  if (code === 0) {
                    setLoadOK(msg);
                    setLivingTypes([[{ value: 0, label: '不限' }, ...data!]]);
                  } else {
                    setLoadFails([...loadFails, msg]);
                  }
                },
              )
              .catch((reason) => {
                setLoadFails([...loadFails, reason]);
              })
              .finally(() => {
                console.log(`${mznmfl6} inner finally!`);
              });
          }
        })
        .catch((reason: any) => {
          console.error(reason);
          setLoadFails([...loadFails, `请求${mznmfl6}时发生错误：${reason}`]);
        })
        .finally(() => {
          console.log(`${mznmfl6} outter finally!`);
          setLoadingTimes(--times);
        });

      // 搜索。
      doSearch()
        .then((rsp: PageResult<Reimb>) => {
          const {
            data,
            code,
            msg,
            page,
            size,
            totalElements,
            totalPages,
            last,
          } = rsp;
          if (code === 0) {
            setData(data!);
            setPageInfo({
              code,
              msg,
              page,
              size,
              totalElements,
              totalPages,
              last,
            });
            setLoadOK(msg);
            setHasMore(!last);
          } else {
            setData([]);
            setLoadFails([...loadFails, msg]);
            setHasMore(false);
          }
        })
        .catch((reason) => {
          setLoadFails([...loadFails, reason]);
        })
        .finally(() => {
          setLoadingTimes(--times);
        });
    } // end authOK
  }
  useEffect(load, [authOK]);

  async function loadMore() {
    console.log('loading more...,current page=', pageInfo.page);
    const rsp = await doSearch(
      searchRef.current?.nativeElement?.value,
      pageInfo.page + 1,
      subject,
      //yearMonth,
      lastLivingType,
      invoiceSupplement,
      applicants,
      createdDateValue,
      dogTypes,
      originTypeTags,
      livingTags,
    );
    const { data, code, msg, page, size, totalElements, totalPages, last } =
      rsp;
    if (code === 0) {
      setData((currents) => [...currents, ...data!]);
      setPageInfo({ code, msg, page, size, totalElements, totalPages, last });
      setLoadOK(msg);
      setHasMore(!last);
    } else {
      setData([]);
      setLoadFails([...loadFails, msg]);
      setHasMore(false);
    }
  }

  if (tokening) {
    return <h3>正在登录...</h3>;
  }
  if (loadingTimes > 0) {
    return <h3>正在加载，还有{loadingTimes}个请求...</h3>;
  }

  return (
    <Page>
      <Content>
        <div className={styles.header}>
          <div className={styles.left}>
            <SearchBar
              ref={searchRef}
              onSearch={(val: string) => {
                setName(val);
              }}
            />
          </div>
          <div className={styles.right}>
            <Button
              size="small"
              color="primary"
              onClick={() => {
                const val = searchRef.current?.nativeElement?.value;
                setName(val);
              }}
            >
              搜索({pageInfo.totalElements})
            </Button>
            <Button size="small" color="default" onClick={expertExcel}>
              导出
            </Button>
          </div>
        </div>
        <div className={styles.filterGroup}>
          <div className={styles.item}>
            <Picker
              columns={livingTypes}
              value={lastLivingType}
              onConfirm={(v: PickerValue[]) => {
                setLastLivingType(v);
              }}
            >
              {(
                items: (PickerColumnItem | null)[],
                { open }: PickerActions,
              ) => (
                <span onClick={open}>
                  {items.every((item) => item === null)
                    ? '最新状态'
                    : items.map((item) => item?.label ?? '未选择').join(' - ')}
                </span>
              )}
            </Picker>
            <DownOutline fontSize={10} />
          </div>
          <div className={styles.line}></div>
          <div className={styles.item}>
            <Picker
              columns={[
                [
                  { label: '不限', value: 'unlimited' },
                  { label: '待支付', value: 'needPaid' },
                ],
              ]}
              value={livingTags}
              onConfirm={(v: PickerValue[]) => {
                setLivingTags(v);
              }}
            >
              {(
                items: (PickerColumnItem | null)[],
                { open }: PickerActions,
              ) => (
                <span onClick={open}>
                  {items.every((item) => item === null)
                    ? '支付'
                    : items.map((item) => item?.label ?? '未选择').join(' - ')}
                </span>
              )}
            </Picker>
            <DownOutline fontSize={10} />
          </div>
          <div className={styles.line}></div>

          <div className={styles.item}>
            <Picker
              columns={[
                [
                  { label: '不限', value: 'unlimited' },
                  { label: '项目', value: 'block' },
                  { label: '商机', value: 'opportunity' },
                  { label: '专项', value: 'specialized' },
                ],
              ]}
              value={originTypeTags}
              onConfirm={(v: PickerValue[]) => {
                setOriginTypeTags(v);
              }}
            >
              {(
                items: (PickerColumnItem | null)[],
                { open }: PickerActions,
              ) => (
                <span onClick={open}>
                  {items.every((item) => item === null)
                    ? '挂接对象'
                    : items.map((item) => item?.label ?? '未选择').join(' - ')}
                </span>
              )}
            </Picker>
          </div>
          <div className={styles.line}></div>
          <div className={styles.item}>
            <Picker
              columns={[
                [
                  { label: '不限', value: 'unlimited' },
                  { label: '待补票', value: 'waitingSupplementInvoice' },
                  {
                    label: '发票补充完成',
                    value: 'invoiceSupplementCompleted',
                  },
                  {
                    label: '待被票或已被票',
                    value: 'waitingOrComplete',
                  },
                  {
                    label: '待我销帐',
                    value: 'waitingMeToWriteOff',
                  },
                ],
              ]}
              onConfirm={(v: PickerValue[]) => {
                setInvoiceSupplement(v);
              }}
            >
              {(
                items: (PickerColumnItem | null)[],
                { open }: PickerActions,
              ) => (
                <span onClick={open}>
                  {items.every((item) => item === null)
                    ? '补票情况'
                    : items.map((item) => item?.label ?? '未选择').join(' - ')}
                </span>
              )}
            </Picker>
          </div>

          <div className={styles.line}></div>
          <div className={styles.item}>
            <span onClick={() => setApplicantPopupVisable(true)}>
              {applicants.length < 1 && '申请人'}
              {applicants.length === 1 && applicants[0].label!}
              {applicants.length > 1 &&
                `${applicants[0].label}等(${applicants.length})`}
            </span>
            <DownOutline fontSize={10} />
          </div>

          <div className={styles.line}></div>
          <div className={styles.item}>
            <span onClick={() => setCreatedDatePopupVisable(true)}>
              {createdDateValue.lastClick ? createdDateValue.tip : '申请时间'}
            </span>
            <DownOutline fontSize={10} />
          </div>

          <div className={styles.line}></div>
          <div className={styles.item}>
            <Cascader
              options={subjects}
              value={subject}
              onConfirm={(v: CheckListValue[], e: CascaderValueExtend) => {
                console.log(e);
                setSubject(v);
              }}
            >
              {(items: (CascaderOption | null)[], actions: CascaderActions) => {
                const index = items.findLastIndex((item) => item !== null);
                return (
                  <span onClick={actions.open}>
                    {index < 0 ? '科目' : items[index]?.label}
                  </span>
                );
              }}
            </Cascader>
            <DownOutline fontSize={10} />
          </div>
          <div className={styles.line}></div>
          <div className={styles.item}>
            <Picker
              columns={[
                [
                  { label: '不限', value: 'unlimited' },
                  {
                    label: '非预期非分摊',
                    value: 'notAnticipatedNotMigrateToIt',
                  },
                  { label: '预期支出', value: 'anticipated' },
                  { label: '补录成本', value: 'history' },
                  { label: '分摊单', value: 'migrateToIt' },
                  { label: '有补票动作', value: 'actCostMoneyIsNotNull' },
                ],
              ]}
              value={dogTypes}
              onConfirm={(v: PickerValue[]) => {
                setDogTypes(v);
              }}
            >
              {(
                items: (PickerColumnItem | null)[],
                { open }: PickerActions,
              ) => (
                <span onClick={open}>
                  {items.every((item) => item === null)
                    ? '单据类型'
                    : items.map((item) => item?.label ?? '未选择').join(' - ')}
                </span>
              )}
            </Picker>
            <DownOutline fontSize={10} />
          </div>
        </div>

        <div className={styles.reimbList + ' cardListGroup'}>
          <List>
            {data.map(
              ({
                id,
                name,
                code,
                finType,
                applicant,
                money,
                actPaidMoey,
                unPaidMoney,
                writeOff,
                reimbMoney,
                createdAt,
                onlyBlock,
                onlyOpportunity,
                oaDepartment,
                oaCompany,
                paid,
                
                waitingSupplementInvoice,
                invoiceSupplementCompleted,
                waitingWriteOff,
                actWaitingWriteOff,
                useInvoicePocket,

                migratedTo,
                migratedFrom,

                history,
                anticipated,
              }) => {
                const advance = finType?.value === 'advance';
                return (
                  <List.Item
                    key={id}
                    description={
                      <>
                        <Grid columns={1} gap={8} style={{ marginTop: '10px' }}>
                          <Grid.Item>申请部门：{oaDepartment?.name}</Grid.Item>
                        </Grid>
                        <Grid columns={1} gap={8} style={{ marginTop: '10px' }}>
                          <Grid.Item> 申请人：{applicant?.name} </Grid.Item>
                        </Grid>
                        <Grid columns={1} gap={8} style={{ marginTop: '10px' }}>
                          <Grid.Item>
                            <Space wrap>
                              申请时间:
                              {dayjs(createdAt).format(DATE_TIME_FORMAT)}
                            </Space>
                          </Grid.Item>
                        </Grid>
                        <Grid columns={1} gap={8} style={{ marginTop: '10px' }}>
                          <Grid.Item>
                            <Space wrap>支付主体:{oaCompany?.label}</Space>
                          </Grid.Item>
                        </Grid>
                      </>
                    }
                    onClick={() => {
                      navigate(`/finance/reimb/detail?id=${id}`);
                    }}
                  >
                    <Grid columns={1} gap={8}>
                      <Grid.Item className="flex">
                        <Tag color={advance ? 'warning' : 'primary'}>
                          {finType?.label}
                        </Tag>
                        &nbsp;
                        {code && (
                          <Tag color={history ? 'warning' : 'primary'}>
                            {code}
                          </Tag>
                        )}{' '}
                        &nbsp;
                        <AuditTalkStautsTip
                          url="/api/reimb-audit-talk"
                          origin={id}
                        />
                      </Grid.Item>
                    </Grid>
                    <Grid columns={1} gap={8}>
                      <Grid.Item>
                        {anticipated && <Tag color={'warning'}>预期支出</Tag>}
                        
                        {/*waitingSupplementInvoice && (
                          <Tag color={'warning'}>待补票</Tag>
                        )*/}
                        {/*invoiceSupplementCompleted && (
                          <Tag color={'success'}>完成补票</Tag>
                        )*/}

                        {paid && <Tag color={'success'}>已支付</Tag>}
                        {useInvoicePocket && (
                          <Tag color={'warning'}>使用票池</Tag>
                        )}
                        {migratedTo && <Tag color="primary">已分摊到单项</Tag>}
                        {migratedFrom && (
                          <Tag color="warning">商机成本分摊生成单据</Tag>
                        )}
                      </Grid.Item>
                    </Grid>
                    <Grid columns={1} gap={8}>
                      <Grid.Item>
                        <h3>
                          {name}({id}){waitingWriteOff>0 
                           && <span style={{color:'#ff6430'}}>，待销帐{numberFormator.format(waitingWriteOff)}</span>}
                        </h3>
                        {onlyBlock && (
                          <h4>
                            {onlyBlock.code ? (
                              <Tag color="#108ee9">合同：{onlyBlock.code}</Tag>
                            ) : (
                              '项目'
                            )}
                            {onlyBlock.label}
                          </h4>
                        )}
                        {onlyOpportunity && (
                          <h4>商机：{onlyOpportunity.label} </h4>
                        )}
                      </Grid.Item>
                    </Grid>
                    <Grid columns={1} gap={8}>
                      <Grid.Item>
                        <h5><Space direction={'horizontal'}>总金额：{numberFormator.format( money)}元，已支付:{actPaidMoey}
                          ，待支付：{unPaidMoney}</Space></h5>                    
                      </Grid.Item>
                    </Grid>
                  </List.Item>
                );
              },
            )}
          </List>
        </div>
        <InfiniteScroll
          loadMore={loadMore}
          hasMore={hasMore}
          threshold={0}
        ></InfiniteScroll>

        <LeadersPopup
          setSelectLeaders={setApplicants}
          url={`/api/reimb/get-applicants`}
          visable={applicantPopupVisable}
          setVisable={setApplicantPopupVisable}
        />
        <DateSelectPopup
          visable={createdDatePopupVisable}
          dateSelectedValue={createdDateValue}
          hide={setCreatedDatePopupVisable}
          setDateSelectedValue={setCreatedDateValue}
        />
      </Content>
    </Page>
  );
};
